package cn.com.open.itembank.controller;

import cn.com.open.itembank.common.GlobalConst;
import cn.com.open.itembank.dto.ReturnModel;
import cn.com.open.itembank.dto.RuleInputModel;
import cn.com.open.itembank.dto.RulesSearchModel;
import cn.com.open.itembank.interceptor.Log;
import cn.com.open.itembank.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * Created by lucky on 2017/7/13.
 */

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;

/**
 * 策略控制器
 */
@RestController
@RequestMapping("/itembank")
public class RuleController extends BaseController {
    private static org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(RuleController.class);

    @Autowired
    private ItemBankRulesRemoteService service;

    //region 新增相关（Create：理论方法 HttpPost）

    //region 添加策略

    /**
     * 添加策略
     *
     * @param request        the request
     * @param response       the response
     * @param itembankId     题库id
     * @param ruleInputModel 策略模型
     * @return return model
     */
    @Log(optType = " 添加策略", optDescription = "添加策略，参数：%s", keyName = "ruleInputModel")
    @PostMapping(value = "/{itembankId}/rules")
    public void addRule(HttpServletRequest request, HttpServletResponse response,
                        @PathVariable(value = "itembankId") String itembankId,
                        @RequestBody RuleInputModel ruleInputModel) {

        String appKey = request.getHeader(appKeyString);
        ReturnModel model = service.addRules(appKey, itembankId, ruleInputModel);

        if (model.getCode() == GlobalConst.ID_NOT_EXIST) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        } else if (model.getCode() == GlobalConst.NO_PERMISSION) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        } else {
            responseJson(request, response, model.getData(), model.getMessage(), model.getCode());
        }
    }

    //endregion

    //region 策略组卷(同步)

    /**
     * 策略组卷(同步)
     *
     * @param itembankId 题库ID
     * @param ruleID     策略id
     * @param paperCount 组卷数量
     * @param paperName  试卷名称
     * @return return model
     */
    @Log(optType = "策略组卷(同步)", optDescription = "策略组卷(同步)，ID：%s", keyName = "ruleID")
    @PostMapping(value = "/{itembankId}/rules/{ruleID}/createtestpaper")
    public void generateTestPaper(HttpServletRequest request, HttpServletResponse response,
                                  @PathVariable(value = "itembankId") String itembankId,
                                  @PathVariable(value = "ruleID") String ruleID,
                                  @RequestParam("paperCount") int paperCount,
                                  @RequestParam("paperName") String paperName) {

        String appKey = request.getHeader(appKeyString);
        ReturnModel model = service.createTestPaper(appKey, itembankId, ruleID, paperCount, paperName);

        if (model.getCode() == GlobalConst.ID_NOT_EXIST) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        } else if (model.getCode() == GlobalConst.NO_PERMISSION) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        } else {
            responseJson(request, response, model.getData(), model.getMessage(), model.getCode());
        }
    }

    //endregion

    //region 策略组卷(异步)

    /**
     * 策略组卷(异步)
     *
     * @param itembankId 题库ID
     * @param ruleID     策略id
     * @param paperCount 组卷数量
     * @param paperName  试卷名称
     * @param backUrl    回调路径
     * @return return model
     */
    @Log(optType = "策略组卷(异步)", optDescription = "策略组卷(异步)，参数：%s", keyName = "ruleInputModel")
    @PostMapping(value = "/{itembankId}/rules/{ruleID}/asynccreatetestpaper")
    public void asyncGenerateTestPaper(HttpServletRequest request, HttpServletResponse response,
                                       @PathVariable(value = "itembankId") String itembankId,
                                       @PathVariable(value = "ruleID") String ruleID,
                                       @RequestParam("paperCount") int paperCount,
                                       @RequestParam("paperName") String paperName,
                                       @RequestParam("backUrl") String backUrl) throws UnsupportedEncodingException {

        String appKey = request.getHeader(appKeyString);
        ReturnModel model = service.asyncGenerateCreateTestPaper(appKey, itembankId, ruleID, paperCount, paperName, backUrl);

        if (model.getCode() == GlobalConst.ID_NOT_EXIST) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        } else if (model.getCode() == GlobalConst.NO_PERMISSION) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        } else {
            responseJson(request, response, model.getData(), model.getMessage(), model.getCode());
        }
    }
    //endregion

    //endregion

    //region 删除相关（Delete：理论方法 HttpDelete）

    //region 删除策略

    /**
     * 删除策略
     *
     * @param request    the request
     * @param response   the response
     * @param itembankId 题库id
     * @param id         策略id
     * @return return model
     */
    @Log(optType = "删除策略", optDescription = "删除策略，ID：%s", keyName = "id")
    @DeleteMapping(value = "/{itembankId}/rules/{id}")
    public void removeRule(HttpServletRequest request, HttpServletResponse response,
                           @PathVariable(value = "itembankId") String itembankId,
                           @PathVariable(value = "id") String id) {

        String appKey = request.getHeader(appKeyString);
        ReturnModel model = service.removeRules(appKey, itembankId, id);

        if (model.getCode() == GlobalConst.SUCCESS) {
            response.setStatus(HttpServletResponse.SC_NO_CONTENT);
        } else if (model.getCode() == GlobalConst.ID_NOT_EXIST) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        } else if (model.getCode() == GlobalConst.NO_PERMISSION) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        } else {
            responseJson(request, response, model.getData(), model.getMessage(), model.getCode());
        }
    }

    //endregion

    //endregion

    //region 更新相关（Update：理论方法 HttpPut）

    //region 修改策略

    /**
     * 修改策略
     *
     * @param request        the request
     * @param response       the response
     * @param itembankId     题库id
     * @param ruleInputModel 策略模型
     * @return return model
     */
    @Log(optType = "修改策略", optDescription = "修改策略，参数：%s", keyName = "ruleInputModel")
    @PutMapping(value = "/{itembankId}/rules/update")
    public void updateRule(HttpServletRequest request, HttpServletResponse response,
                           @PathVariable(value = "itembankId") String itembankId,
                           @RequestBody RuleInputModel ruleInputModel) {

        String appKey = request.getHeader(appKeyString);
        ReturnModel model = service.updateRules(appKey, itembankId, ruleInputModel);

        if (model.getCode() == GlobalConst.ID_NOT_EXIST) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        } else if (model.getCode() == GlobalConst.NO_PERMISSION) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        } else {
            responseJson(request, response, null, model.getMessage(), model.getCode());
        }
    }

    //endregion

    //region 修改策略状态

    /**
     * 修改策略状态
     *
     * @param request    the request
     * @param response   the response
     * @param itembankId 题库id
     * @param id         策略id
     * @return return model
     */
    @Log(optType = "修改策略状态", optDescription = "修改策略状态，ID：%s", keyName = "id")
    @PutMapping(value = "/{itembankId}/rules/{id}/status")
    public void updateRuleStatus(HttpServletRequest request, HttpServletResponse response,
                                 @PathVariable(value = "itembankId") String itembankId,
                                 @PathVariable(value = "id") String id) {

        String appKey = request.getHeader(appKeyString);
        ReturnModel model = service.updateRulesStatus(appKey, itembankId, id);

        if (model.getCode() == GlobalConst.ID_NOT_EXIST) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        } else if (model.getCode() == GlobalConst.NO_PERMISSION) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        } else {
            responseJson(request, response, model.getData(), model.getMessage(), model.getCode());
        }
    }

    //endregion

    //endregion

    //region 查询相关（Retrieve：理论方法 HttpGet）

    //region 获取策略信息

    /**
     * 获取策略信息
     *
     * @param request    the request
     * @param response   the response
     * @param itembankId 题库id
     * @param id         策略id
     * @return return model
     */
    @Log(optType = " 获取策略信息", optDescription = "获取策略信息，ID：%s", keyName = "id")
    @GetMapping(value = "/{itembankId}/rules/{id}")
    public void getRule(HttpServletRequest request, HttpServletResponse response,
                        @PathVariable(value = "itembankId") String itembankId,
                        @PathVariable(value = "id") String id) {

        String appKey = request.getHeader(appKeyString);
        ReturnModel model = service.getRuleInfo(appKey, itembankId, id);

        if (model.getCode() == GlobalConst.ID_NOT_EXIST) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        } else if (model.getCode() == GlobalConst.NO_PERMISSION) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        } else {
            responseJson(request, response, model.getData(), model.getMessage(), model.getCode());
        }
    }

    //endregion

    //region 获取策略列表

    /**
     * 获取策略列表
     *
     * @param request          the request
     * @param response         the response
     * @param itembankId       题库id
     * @param rulesSearchModel 策略模型
     * @return return model
     */
    @Log(optType = "获取策略列表", optDescription = "获取策略列表，题库ID：%s", keyName = "itembankId")
    @PostMapping(value = "/{itembankId}/getrulelist")
    public void getRuleList(HttpServletRequest request, HttpServletResponse response,
                            @PathVariable(value = "itembankId") String itembankId,
                            @RequestBody RulesSearchModel rulesSearchModel) {

        String appKey = request.getHeader(appKeyString);
        ReturnModel model = service.getRulesList(appKey, itembankId, rulesSearchModel);

        if (model.getCode() == GlobalConst.ID_NOT_EXIST) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        } else if (model.getCode() == GlobalConst.NO_PERMISSION) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        } else {
            responseJson(request, response, model.getData(), model.getMessage(), model.getCode());
        }
    }

    //endregion

    //endregion
}
